﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.Collections;
using Maticsoft.Common;
using Hyfw.BLL;

namespace Web.Manage.User
{
    public partial class AjaxService : System.Web.UI.Page
    {
        #region 业务逻辑类
        CommonManager commonManager = new CommonManager();
        CharacterManager characterManager = new CharacterManager();
        UserManager userManager = new UserManager();
        #endregion


        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");

            try
            {
                BeforeInvoke(methodName);
                method.Invoke(this, null);
            }
            catch (Exception ex)
            {
                Hashtable result = new Hashtable();
                result["error"] = -1;
                result["message"] = ex.Message;
                result["stackTrace"] = ex.StackTrace;
                String json = JSON.Encode(result);
                Response.Clear();
                Response.Write(json);
            }
            finally
            {
                AfterInvoke(methodName);
            }
        }

        //权限管理
        protected void BeforeInvoke(String methodName)
        {
            //Hashtable user = GetUser();
            //if (user.role == "admin" && methodName == "remove") throw .      
        }
        //日志管理
        protected void AfterInvoke(String methodName)
        {

        }
        //=============================================================

        #region

        public void SaveUser()
        {
            string json = Request["data"];

            ArrayList rows = (ArrayList)JSON.Decode(json);
            foreach (Hashtable row in rows)
            {
                String id = row["id"] != null ? row["id"].ToString() : "";
                //根据记录状态，进行不同的增加、删除、修改操作
                String state = row["_state"] != null ? row["_state"].ToString() : "";

                if (state == "added" || id == "")           //新增：id为空，或_state为added
                {
                    row["createDate"] = DateTime.Now;
                    userManager.Add(row);
                }
                else if (state == "removed" || state == "deleted")
                {
                    userManager.Delete(int.Parse(id));
                }
                else if (state == "modified" || state == "") //更新：_state为空或modified
                {
                    userManager.Update(row);
                }
            }
        }

        public void GetUser()
        {
            string id = Request["id"];
            Hashtable ht = userManager.GetUser(int.Parse(id));
            string json = JSON.Encode(ht);
            Response.Write(json);
        }

        public void GetRoles()
        {
            Hashtable ht = (Hashtable)Session["userInfo"];
            int roleId = int.Parse(ht["roleId"].ToString());
            ArrayList data = characterManager.GetRoles(roleId);
            string json = JSON.Encode(data);
            Response.Write(json);
        }

        public void GetLimits()
        {
            Hashtable ht = (Hashtable)Session["userInfo"];
            int roleId = int.Parse(ht["roleId"].ToString());
            ArrayList data = userManager.GetLimits(roleId);
            string json = JSON.Encode(data);
            Response.Write(json);
        }

        public void GetMenu()
        {

        }

        public void SearchUsers()
        {
            //查询条件
            string key = Request["key"];
            //分页
            int pageIndex = Convert.ToInt32(Request["pageIndex"]);
            int pageSize = Convert.ToInt32(Request["pageSize"]);
            //字段排序
            String sortField = Request["sortField"];
            String sortOrder = Request["sortOrder"];

            //业务层：数据库操作
            Hashtable result = commonManager.Serach(key, pageIndex, pageSize, sortField, sortOrder, "User_GetList");

            //JSON
            String json = JSON.Encode(result);
            Response.Write(json);
        }

        public void Login()
        {
            string userName = Request["username"];
            string password = Request["pwd"];
            int returnValue;
            ArrayList list = new UserManager().Login(userName, password, out returnValue);
            Hashtable table = null;
            if (list != null)
            {
                table = (Hashtable)list[0];
            }
            Session.Add("userInfo", table);
            if (returnValue > 0)
            {

                Response.Write("1");
            }
            else
            {
                Response.Write("0");
            }
        }

        public void RemoveUsers()
        {
            String idStr = Request["id"];
            if (String.IsNullOrEmpty(idStr)) return;
            String[] ids = idStr.Split(',');
            for (int i = 0, l = ids.Length; i < l; i++)
            {
                string id = ids[i];
                userManager.Delete(int.Parse(id));
            }
        }

        public void UserNameValidation()
        {
            string userName = Request["userName"];
            bool result = userManager.UserNameExist(userName);
            if (result)
            {
                Response.Write("1");
            }
            else
            {
                Response.Write("0");
            }

        }
        #endregion
    }
}